import {IS_FOR_WX} from "../../AppConfig";

if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
  let makeShareQueryString = require("./WechatMakeShareQueryString");
  const minShareDiffSec = 5; //最小分享拉起时间, 小于此值, 分享视为失败
  
  let shareToFriends = function (opts, shareParams) {
    let beginShareTime;
    let endShareTime;
    let shareOnShow = function () {
      cc.game.off(cc.game.EVENT_SHOW, shareOnShow);
      cc.game.off(cc.game.EVENT_HIDE, shareOnHide);
      endShareTime = new Date().getTime();
      let diffSec = (endShareTime - beginShareTime) / 1000;
      console.log("shareOnShow", diffSec);
      let success = false;
      
      if (opts.mustSuccess || Global.SwitchSettings.getShareMustSuccess()) {
        success = true;
      } else {
        if (diffSec > minShareDiffSec) {  //必须大于最小时间
          let shareTimes = Global.ShareWatchAdSwitch.getShareTimes();
          if (shareTimes === 0) {  //每天第一次必失败
            success = false;
          } else if (shareTimes < 4) { //第2,3,4次必成功
            success = true
          } else {   //大于4次后, 30%几率失败
            let odds = Math.floor(Math.random() * 100);
            if (odds < 30) {
              success = false;
            }
          }
        }
      }
      
      if (!success) {
        opts.mustSuccess = true;
        wx.showModal({
          title: '提示',
          content: '分享失败，请发送到微信群!',
          showCancel: true,
          success: function (res) {
            if (res.cancel) {
              //点击取消,默认隐藏弹框
            } else {
              //点击确定, 再次拉起分享
              shareToFriends(opts, shareParams);
            }
          },
          fail: function (res) {
            if (opts.fail) {
              let res = {};
              opts.fail.success(res);
            }
            
          },//接口调用失败的回调函数
          complete: function (res) {
          },//接口调用结束的回调函数（调用成功、失败都会执行）
        });
        
        
      } else {
        if (opts.success) {
          let res = {};
          opts.success(res);
        }
      }
    };
    
    let shareOnHide = function () {
      beginShareTime = new Date().getTime();
      console.log("shareOnHide");
    };
    let query = makeShareQueryString(shareParams);
    cc.game.on(cc.game.EVENT_SHOW, shareOnShow);
    cc.game.on(cc.game.EVENT_HIDE, shareOnHide);
    
    // wx.shareAppMessage({
    wx.aldShareAppMessage({
      title: opts.title,
      imageUrl: opts.imageUrl,
      imageUrlId: opts.imageUrlId,
      ald_desc: opts.logKey,
      query,
    });
  };
  
  
  module.exports = {
    shareToFriends,
  }
}